/*
 * 如果是被包含的文件，尽量选择为.hpp而非.cpp，否则可能陷入重复包含
 * */
#include "13_EchoServer.hpp"
#include "15_DefaultMessageHandler.hpp"
#include "15_Mytask.hpp"
#include <iostream>
#include <csignal>

#define info_msg(msg) do { \
    printf("%s | %d | %s | %s \n", __FILE__, __LINE__, __FUNCTION__, msg); \
} while(0)

namespace xy
{
// 声明一个外部变量来访问服务器实例
//xy::TcpServer* g_server = nullptr;
Echo_Server* Echo_Server::_instance = nullptr;

Echo_Server::Echo_Server(unsigned short port, const std::string& ip, int thread_num, int que_size)
    :_tcpserver(port, ip)
    ,_thread_pool(thread_num, que_size)
    ,_is_running(false)
    ,_message_handler1(std::make_shared<DefaultMessageHandler>())
    ,_message_handler2(std::make_shared<Mytask>())
    {
        _instance = this;   // 设置实例指针
    }

void Echo_Server::start()
{
    if(_is_running == true)
    {
        info_msg("Start failure: Echo_Server is already running.");
        return;
    }
    signal(SIGINT, signal_handler);  // 注册信号处理函数
    _thread_pool.start();

    //设置回调函数
    _tcpserver.get_event_loop().set_connection_callback(std::bind(&Echo_Server::on_connection, this, std::placeholders::_1));
    _tcpserver.get_event_loop().set_message_callback(std::bind(&Echo_Server::on_message, this, std::placeholders::_1, std::placeholders::_2));
    _tcpserver.get_event_loop().set_close_callback(std::bind(&Echo_Server::on_close, this, std::placeholders::_1));

    _tcpserver.start();
    _is_running = true;
}

void Echo_Server::stop()
{
    if(_is_running == false)
    {
        info_msg("Stop failure: Echo_Server has already stopped.");
        return;
    }

    _thread_pool.stop();
    _tcpserver.stop();
    _is_running = false;

}

// 处理ctrl + c信号，优雅退出
void Echo_Server::signal_handler(int signum)
{
    if(_instance)
    {
        info_msg("Received signal, server shutting down...");
        _instance->stop();
    }
    else{
        info_msg("_instance not exist.");
    }
    //exit(0);      // 移出exit(0)调用，因为在TcpServer::stop()中已经准备关闭代码
}

// 定义回调函数
void Echo_Server::on_connection(const TCPconnection::TCPconnectionPtr& conn)
{
    std::cout << "New connection established: " << conn->tostring() << "\n";
}

// 内部方法：将消息处理调度到线程池
void Echo_Server::on_message(const TCPconnection::TCPconnectionPtr& conn, const std::string &msg)
{
    std::cout << "Received message:\n " << conn->tostring();
    _thread_pool.addTask(
        [this, conn, msg](){
            // 在线程池中处理消息
            std::string response = handle_message1(msg);
            // 发送响应
            conn->send(response);
        }
    );
}

void Echo_Server::on_close(const TCPconnection::TCPconnectionPtr& conn)
{
    std::cout << "Connection closed: " << conn->tostring() << "\n";
}
    
// 默认消息的实现（用户可以重写）
std::string Echo_Server::handle_message1(const std::string& msg)
{
    return _message_handler1->handle(msg);

}

}

